package weifei.live.simulation.im.entity;


import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import org.springframework.stereotype.Repository;
import weifei.live.simulation.im.cmd.Message;


@Data
@EqualsAndHashCode(callSuper = true)
@TableName("group_user_message_cache")
@Repository
public class GroupUserMessageCache extends Model<GroupUserMessageCache>
{
    @Getter
    public enum Column
    {
        ID("id"),
        GroupID("group_id"),
        Type("type"),
        Format("format"),
        SenderID("sender_id"),
        Content("content"),
        SendTime("send_time"),
        CacheTime("cache_time");

        final String name;
        Column(String name) { this.name = name; }
    }


    @TableId
    private Integer id;
    private Integer groupId;
    private Message.Type type;
    private Message.Format format;
    private Integer senderId;
    private String content;
    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    private java.util.Date sendTime;
    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    private java.util.Date cacheTime;


    /** 做数据库修改用 */
    public GroupUserMessageCache() {}
    public GroupUserMessageCache(
            Integer groupId,
            Message.Type type,
            Message.Format format,
            Integer senderId,
            String content,
            java.util.Date sendTime
    )
    {
        this.groupId = groupId;
        this.type = type;
        this.format = format;
        this.senderId = senderId;
        this.content = content;
        this.sendTime = sendTime;
    }


    public Message toMessage()
    {
        // 广播给所有群聊的消息
        if (this.senderId == null && this.groupId == null)
        {
            return new Message(
                this.type,
                this.format,
                Message.Destination.Group,
                null,
                null,
                this.content,
                this.sendTime
            );
        }

        // 广播给部分群聊的消息
        // this.groupId 为 null 已排除
        if (this.senderId == null)
        {
            return new Message(
                this.type,
                this.format,
                Message.Destination.Group,
                null,
                new Integer[]{this.groupId},
                this.content,
                this.sendTime
            );
        }


        // 用户发到群的消息
        return new Message(
            this.type,
            this.format,
            Message.Destination.UserToGroup,
            this.senderId,
            new Integer[]{this.groupId},
            this.content,
            this.sendTime
        );
    }
}

